
//
//  AddressManagerViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/1.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "AddressManagerViewController.h"
#import "AddNewAddressViewController.h"
#import "AddressManagerCell.h"
@interface AddressManagerViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tablview;
@property(nonatomic,strong)NSMutableArray *dataArray;


@end

@implementation AddressManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地址管理";
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    if (self.isFromSetting) {
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake(0, 6, 67, 23);
        UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
        backImg.frame = CGRectMake(-10, 0, 22, 22);
        [backBtn addSubview:backImg];
        UILabel *backText = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 65, 22)];
//        backText.text = @"返回";
        backText.font = [UIFont systemFontOfSize:17];
        [backText setBackgroundColor:[UIColor clearColor]];
        [backText setTextColor:[UIColor whiteColor]];
        [backBtn addSubview:backText];
        [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
        [self.navigationItem setLeftBarButtonItem:leftButton];

    }
    self.tabBarController.tabBar.hidden = YES;
    [self.dataArray removeAllObjects];
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSLog(@"%@",sessionId);
    [self getDataInformation];
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
-(void)createTablview{
    UIButton *addNewAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addNewAddressBtn addTarget:self action:@selector(addNewAddress:) forControlEvents:UIControlEventTouchUpInside];
    addNewAddressBtn.backgroundColor = COLOR_HEX(0xffc91f);
    [addNewAddressBtn setTitle:@"添加新地址"forState:UIControlStateNormal];
    [self.view addSubview:addNewAddressBtn];
    [addNewAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.bottom.equalTo(self.view).offset(0);
        make.height.mas_equalTo(scaleTopAndBottom(50));
    }];
    self.tablview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tablview];
    [self.tablview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.bottom.equalTo(addNewAddressBtn.mas_top);
    }];
    self.tablview.dataSource = self;
    self.tablview.delegate = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    self.tablview.tableFooterView  = view;
    [self.tablview registerClass:[AddressManagerCell class] forCellReuseIdentifier:@"AddressManagerCell"];
    self.tablview.estimatedRowHeight = 200;
}

-(void)createUI{
    UIButton *addNewAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addNewAddressBtn addTarget:self action:@selector(addNewAddress:) forControlEvents:UIControlEventTouchUpInside];
    addNewAddressBtn.backgroundColor = COLOR_HEX(0xffc91f);
    [addNewAddressBtn setTitle:@"添加新地址"forState:UIControlStateNormal];
    [self.view addSubview:addNewAddressBtn];
    [addNewAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.bottom.equalTo(self.view).offset(0);
        make.height.mas_equalTo(scaleTopAndBottom(50));
    }];
    UIImageView *imageView = [[UIImageView alloc] init];
//    imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view).offset(0);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.bottom.equalTo(addNewAddressBtn.mas_top);
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressManagerCell"];
    cell.defalutBlock = ^(NSString *addressId) {
        [self chooseAddressIsDefaultAdressWithAddressId:addressId];
    };
    cell.model = self.dataArray[indexPath.row];
    cell.delBtn.tag = 10000 + indexPath.row;
    [cell.delBtn addTarget:self action:@selector(deleteAddressInforma:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressModel *model = self.dataArray[indexPath.row];
    self.addressBlock(model);
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)deleteAddressInforma:(UIButton *)btn{
    dispatch_queue_t gloabQue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloabQue, ^{
        NSIndexPath *index = [NSIndexPath indexPathForRow:btn.tag - 10000 inSection:0];
        AddressModel *model = self.dataArray[index.row];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *url = ServerIp@"/addressApp/delAddress";
        NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
        NSDictionary *param = @{@"addressId":model.Id,@"sessionId":sessionId};
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            [self.dataArray removeObjectAtIndex:index.row];
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.tablview reloadData];
            });
            
            NSLog(@"%@",jsonDic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];
 
    });
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

-(void)addNewAddress:(UIButton *)btn{
    AddNewAddressViewController *addVc = [[AddNewAddressViewController alloc] init];
    [self.navigationController pushViewController:addVc animated:YES];
}
#pragma mark
-(void)getDataInformation{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/addressApp/addressList";
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *param = @{@"sessionId":sessionId};
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *listArra = jsonDic[@"list"];
        if (listArra.count == 0) {
            [self createUI];
        }else{
            for (UIView *view in self.view.subviews) {
                [view removeFromSuperview];
            }
            [self createTablview];
            for (NSDictionary *pacDic in listArra) {
                AddressModel *model = [AddressModel modelWithDictionary:pacDic];
                [self.dataArray addObject:model];
            }
            NSLog(@"%@",jsonDic);
            [self.tablview reloadData];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

/**
 选择机构为默认
 */
-(void)chooseAddressIsDefaultAdressWithAddressId:(NSString *)addressID{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/addressApp/setDefaultAddress";
    NSString *sessionID = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:sessionID,@"sessionId",addressID,@"addressId", nil];
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsondic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([jsondic[@"msg"] isEqual:@"操作成功"]) {
            [self.dataArray removeAllObjects];
            [self getDataInformation];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
